import Util from './utils';

class Payment {
    constructor() {}

    pay(opts) {
        if (!opts) throw new Error('missing paramter opts');

        return new Promise((resolve, reject) => {
            Util.getProvider('payment')
                .then(res => {
                    const paymentParams = {
                        provider: res[0],
                        orderInfo: opts.orderInfo || opts,
                        timeStamp: opts.pay_info.timestamp + '',
                        nonceStr: opts.pay_info.noncestr,
                        package: opts.pay_info.package,
                        signType: opts.pay_info.sign_type,
                        paySign: opts.pay_info.pay_sign,
                        success: res => this.handlePaymentSuccess(res, opts, resolve),
                        fail: err => this.handlePaymentFailure(err, reject),
                    };

                    uni.requestPayment(paymentParams);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    handlePaymentSuccess(res, opts, resolve) {
        resolve({
            orderId: opts.id,
        });
    }

    handlePaymentFailure(err, reject) {
        let msg = '';
        if (err && err.errMsg && err.errMsg.indexOf('cancel') > -1) {
            msg = 'cancel';
        } else {
            msg = err;
        }
        reject({
            msg: msg,
        });
    }
}

export default new Payment();
